let args = location.search;
let keyword = ''; // 关键字
let pc = ''; // 当前页码
let term = 0; // 条件
let price = ''; // 最小价格-最大价格
if(args) {
	args = args.substring(1);
	let params = args.split('&');
	params.forEach(item => {
		if(item.startsWith('keyword=') && item.length > 8) {
			keyword = decodeURI(item.split('=')[1]);
		}
		if(item.startsWith('pc=') && item.length > 3) {
			pc = decodeURI(item.split('=')[1]);
		}
		if(item.startsWith('term=') && item.length > 5) {
			term = parseInt(decodeURI(item.split('=')[1]));
			if(term != term) {
				// NaN
				term = 0;
			}
		}
		if(item.startsWith('price=') && item.length > 6) {
			price = decodeURI(item.split('=')[1]);
		}
	});
}
//搜索框
let searchContents = document.querySelectorAll('.header-m input');
for(let i = 0; i < searchContents.length; i++) {
	let searchContent = searchContents[i];
	let searchButton = searchContent.nextElementSibling;
	searchContent.placeholder = keyword;
	searchButton.onclick = function() {
		let searchValue = searchContent.value.trim();
		if(searchValue) {
			location.href = '/page/user/search/list.html?keyword=' + searchValue;
		} else if(searchContent.placeholder != '搜索商品') {
			location.href = '/page/user/search/list.html?keyword=' + searchContent.placeholder;
		}
	}
	searchContent.onkeydown = function(e) {
		e = e || window.event;
		if(e.keyCode == 13 || e.keyCode == 108) {
			// 回车键
			searchButton.click();
		}
	}
}
let contentWrap = document.querySelector('.main .content-wrap');
// 商品列表
ajax({
	type: 'POST',
	url: '/goods/search',
	async: true,
	data: {
		keyword: keyword,
		pc: pc,
		term: term,
		price: price
	},
	success: function(xhr) {
		let arg = JSON.parse(xhr.responseText);
		let resultCount = document.getElementById('resultCount')
		if(arg.code == 3110) {
			// 若没有数据则显示无数据画面
			let goodsList = contentWrap.querySelector('.goods-list');
			let contentPage = goodsList.nextElementSibling
			goodsList.style.dispaly = 'none';
			contentPage.style.dispaly = 'none';
			let noticeWrap = document.createElement('div');
			noticeWrap.className = 'notice-wrap';
			noticeWrap.innerHTML = `<span></span>
						<div class="notice">抱歉，没有找到与"<em>${keyword}</em>"相关的商品</div>`;
			contentWrap.appendChild(noticeWrap)
			removeWorld(goodsList);
			removeWorld(contentPage);
			resultCount.innerText = 0;
			// 搜索框改变placeholder
			for(let i = 0; i < searchContents.length; i++) {
				let searchContent = searchContents[i];
				searchContent.placeholder = '搜索商品';
			}
		} else if(arg.code == 200) {
			// 设置商品总数
			let pc = arg.data.pc; // 当前页码
			let tp = arg.data.tp; // 总页数
			let tr = arg.data.tr; // 数据总量
			resultCount.innerText = tr;
			let goodsListUl = document.querySelector('.main .goods-list ul');
			let dataArray = arg.data.beanList;
			dataArray.forEach(data => {
				let li = document.createElement('li');
				li.className = 'goods-item';
				let _imgPath = data.imgPath;
				// 若有多张图片则取第一张
				let imgPathIndex = _imgPath.indexOf(';');
				if(imgPathIndex != -1) {
					_imgPath = _imgPath.substring(0, imgPathIndex);
				}
				li.innerHTML = `<div class="fl">
								<a href="/page/user/search/desc.html?${data.gid}">
									<img src="${_imgPath}" alt="商品图片" />
								</a>
							</div>
							<div class="goods-item-r fr">
								<a href="/page/user/search/desc.html?${data.gid}" class="goods-item-title">${data.name}</a>
								<strong>${data.realPrice}</strong>
								<div class="goods-item-label clearfix">
								</div>
								<p class="goods-item-desc">${data.details}</p>
								<p class="goods-item-info">
									<span class="goods-item-views">浏览量：${data.view}</span>
								</p>
								<div class="goods-item-buy">
									<a href="/page/user/search/desc.html?${data.gid}">查看详情</a>
									<a href="javascript:void(0)">加入购物车</a>
									<a href="javascript:void(0)">立即预约</a>
								</div>
							</div>`;
				// 设置商品标签
				let goodsLabel = li.querySelector('.goods-item-label');
				let labels = data.label.split('####TPL####');
				labels.forEach(label => {
					let labelDiv = document.createElement('div');
					labelDiv.innerText = label;
					goodsLabel.appendChild(labelDiv);
				});
				let toBuy = li.querySelector('.goods-item-buy');
				// 加入购物车
				toBuy.children[1].onclick = function(){
					ajax({
						type: 'POST',
						async: true,
						url: '/cart/add',
						data: {
							id: data.gid,		
							count: 1
						},
						success: function(xhr) {
							let arg = JSON.parse(xhr.responseText);
							if(arg.code == 200) {
								toast('成功加入购物车', '#84cc77');
							} else if(arg.code == 3020) {
								location.href = '/page/user/login.html';
							} else if(arg.code == 3202) {
								mask.style.display = 'block';
								mask.innerHTML = `<div class="mask-wrap" style="position: absolute; top: 50%; left: 50%; margin-top: -59px;margin-left: -195px;width: 390px;background-color: #fff;border-radius: 4px;border: 1px solid #ddd;box-shadow: 0 0 7px #eee;">
									<div class="mask-h clearfix">
										<span style="float: left;width: 34px;height: 34px;background: url(/images/tip_icon.png) no-repeat;margin-top: 10px;margin-left: 10px;"></span>
										<span style="float: left;height: 53px;line-height: 53px;padding-left: 10px;font-size: 14px;">提示</span>
										<span style="float: right;width: 24px;height: 24px;background: url(/images/x_icon.png) no-repeat;cursor: pointer;margin-top: 9px;margin-right: 8px;" title="关闭面板" ></span>
									</div>
									<div class="mask-content" style="padding: 5px 22px;padding-bottom: 40px;font-size: 14px;">${arg.message}</div>
							  	</div>`;
								let maskH = mask.querySelector('.mask-h');
								maskH.children[2].onclick = function() {
									// 顶部关闭icon
									removeAllChildren(mask);
									mask.style.display = 'none';
								}
								setTimeout(() => {
									removeAllChildren(mask);
									mask.style.display = 'none';
								}, 4000);
							} else {
								toast('系统繁忙，请刷新页面后重试', 3000);
							}
						}
					});
				}
				// 预约
				toBuy.children[2].onclick = function(){
					ajax({
						type: 'POST',
						async: true,
						url: '/order/add',
						data: {
							id: data.gid,		
							count: 1
						},
						beforeSend: function() {
							// 显示等待图片
							mask.style.display = 'block';
							mask.style.backgroundColor = 'rgba(0, 0, 0, 0)';
							mask.innerHTML = `<div class="mask-wrap" style="position: absolute; top: 50%; left: 50%; margin-top: -45px;margin-left: -45px;width: 90px;height: 90px;background: url(/images/loading2.gif) no-repeat;background-size: 90px;">
												  </div>`;
						},
						success: function(xhr) {
							removeAllChildren(mask);
							mask.style.display = 'none';
							let arg = JSON.parse(xhr.responseText);
							if(arg.code == 200) {
								location.href = '/page/user/buy/order.html?' + arg.data;
							} else if(arg.code == 3020) {
								location.replace('/page/user/login.html');
							} else if(arg.code == 3300) {
								toast(arg.message);
							} else if(arg.code == 3101) {
								toast('请先完善您的个人信息');
							} else {
								toast('系统繁忙，请刷新页面后重试', 3000);
							}
						}
					});	
				}
				goodsListUl.appendChild(li);
			});
			let contentPage = goodsListUl.parentNode.nextElementSibling;
			let pageNumber = contentPage.children[0];
			function setPageNumber(number) {
				let a = document.createElement('a');
				a.href = `/page/user/search/list.html?keyword=${keyword}&pc=${number}&price=${price}&term=${term}`;
				a.innerText = number;
				pageNumber.appendChild(a);
			}
			// 设置上一页
			if(pc != 1) {
				let front = document.createElement('a');
				front.className = 'front';
				front.href = `/page/user/search/list.html?keyword=${keyword}&pc=${pc-1}&price=${price}&term=${term}`;
				front.innerText = '上一页';
				pageNumber.appendChild(front);
			}
			// 设置中间页码
			if(pc <= 6) {
				if(tp >= 10) {
					for(let number = 1; number <= 10; number++) {
						setPageNumber(number);
					}
				} else {
					for(let number = 1; number <= tp; number++) {
						setPageNumber(number);
					}
				}
			} else {
				if(tp >= pc + 4) {
					for(let number = (pc - 5); number <= (pc + 4); number++) {
						setPageNumber(number);
					}
				} else {
					if(tp <= 10) {
						for(let number = 1; number <= tp; number++) {
							setPageNumber(number);
						}
					} else {
						for(let number = (tp - 9); number <= tp; number++) {
							setPageNumber(number);
						}
					}
				}
			}
			// 设置下一页
			if(pc != tp) {
				let back = document.createElement('a');
				back.className = 'back';
				back.href = `/page/user/search/list.html?keyword=${keyword}&pc=${pc+1}&price=${price}&term=${term}`;
				back.innerText = '下一页';
				pageNumber.appendChild(back);
			}
			// 设置当前页码
			for(let number = 0; number < pageNumber.children.length; number++) {
				if(pc == pageNumber.children[number].innerText) {
					pageNumber.children[number].className = 'active';
					pageNumber.children[number].href = 'javascript:void(0)';
				}
			}
			// 设置去第几页
			if(tp > 10) {
				let toPage = contentPage.children[1];
				toPage.innerHTML = `<span class="page-total">共${tp}页</span>
						<span>到第</span>
						<input type="text" value="1" />
						<span>页</span>
						<button>确定</button>`;
				toPage.children[4].onclick = function() {
					let value = toPage.children[2].value.trim();
					location.href = `/page/search/list.html?keyword=${keyword}&pc=${value}&price=${price}&term=${term}`;
				}
			}
		}
	}
});
// 精选商品
ajax({
	type: 'POST',
	url: '/goods/search',
	async: true,
	data: {
		keyword: keyword,
		pc: '',
		term: 3,
		price: ''
	},
	success: function(xhr) {
		let arg = JSON.parse(xhr.responseText);
		if(arg.code == 200) {
			let dataArray = arg.data.beanList;
			let goodsCarefulUl = document.querySelector('.main .goods-careful ul');
			let count = 0; 
			dataArray.forEach(data => {
				// 最多显示5个精选商品
				if(++count <= 5) {
					let li = document.createElement('li');
					let _imgPath = data.imgPath;
					// 若有多张图片则取第一张
					let imgPathIndex = _imgPath.indexOf(';');
					if(imgPathIndex != -1) {
						_imgPath = _imgPath.substring(0, imgPathIndex);
					}
					li.innerHTML = `<div>
										<a href="/page/user/search/desc.html?${data.gid}">
											<img src="${_imgPath}" alt="精品推荐" />
											<p>${data.details}</p>
										</a>
										<strong>${data.realPrice}</strong>
									</div>`;
					goodsCarefulUl.appendChild(li);	
				}
			});
		}
	}
});
/* 页面移动头部移动 */
let headerMove = document.getElementById('headerMove'); // 头部移动栏
/*
	功能：解决获取页面滚动距离兼容性问题
*/
function getScrollTop() {
	return document.body.scrollTop || document.documentElement.scrollTop;
}
document.onscroll = function() {
	let scrollTop = getScrollTop();
	if(scrollTop >= 195) {
		headerMove.style.display = 'block';
	} else {
		headerMove.style.display = 'none';
	}
}
let filterCommon = contentWrap.querySelector('.filter-common');
for(let i = 0; i < filterCommon.children.length; i++) {
	filterCommon.children[i].href = `/page/user/search/list.html?keyword=${keyword}&term=${i}&price=${price}`;
	if(i == term) {
		filterCommon.children[i].className = filterCommon.children[i].className + ' current';
	}
}
/* 设置鼠标移入条件筛选栏的价格事件 */
let filterPriceSet = document.getElementById('filterPriceSet');
let filterPriceEdit = document.getElementById('filterPriceEdit');
let filterPriceCancel = null;
let filterPriceSubmit = null;
let minInput = filterPriceSet.querySelectorAll('input')[0];
let maxInput = filterPriceSet.querySelectorAll('input')[1];
//给minInput和maxInput赋值
if(price) {
	if(price.indexOf("-") != -1 && price.split("-").length == 2) {
		let minStr = price.split("-")[0];
		let maxStr = price.split("-")[1];
		if(/^[1-9]\d{0,9}$/.test(minStr) && /^[1-9]\d{0,9}$/.test(maxStr)) {
			let min = Number(minStr);
			let max = Number(maxStr);
			if(min > max) {
				let temp = min;
				min = max;
				max = temp;
			}
			minInput.value = min;
			maxInput.value = max;
		}
	}
}
filterPriceSet.onmouseover = function() {
	filterPriceEdit.style.display = 'block';
	filterPriceCancel = filterPriceEdit.querySelector('.price-cancel');
	filterPriceSubmit = filterPriceEdit.querySelector('.price-submit');
	minInput.onkeydown = function(e) {
		e = e || window.event;
		if((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <=105) || e.keyCode == 8 || e.keyCode == 110) {
			return true;
		}else {
			return false;
		}
	}
	maxInput.onkeydown = function(e) {
		e = e || window.event;
		if((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <=105) || e.keyCode == 8 || e.keyCode == 110) {
			return true;
		}else {
			return false;
		}
	}
	filterPriceCancel.onclick = function() {
		minInput.value = '';
		maxInput.value = '';
	}
	filterPriceSubmit.onclick = function() {
		let maxPrice = Number(maxInput.value);
		let minPrice = Number(minInput.value);
		if(maxPrice < minPrice) {
			let temp = maxPrice;
			maxPrice = minPrice;
			minPrice = temp;
		}
		location.href = '/page/user/search/list.html?keyword=' + keyword + '&price=' + minPrice + '-' + maxPrice;
	}
}
filterPriceEdit.onmouseleave = function() {
	filterPriceEdit.style.display = 'none';
	filterPriceCancel.onclick = null;
	filterPriceCancel = null;
	filterPriceSubmit.onclick = null;
	filterPriceSubmit = null;
}
let contentFilter = document.querySelector('.main .main-content');
contentFilter.onmouseenter = function() {
	if(filterPriceEdit.style.display = 'block') {
		filterPriceEdit.style.display = 'none';
	}
}
document.querySelector('.header').onclick = function() {
	if(filterPriceEdit.style.display = 'block') {
		filterPriceEdit.style.display = 'none';
	}
}
/* 设置鼠标移入elevat事件 */
let elevator = document.getElementById('elevator');
let cartItem = elevator.querySelectorAll('.elevator-inner')[0];
let feedbackItem = elevator.querySelectorAll('.elevator-inner')[1];
let toTopItem = elevator.querySelectorAll('.elevator-inner')[2];
cartItem.parentNode.onmouseover = function() {
	cartItem.previousElementSibling.style.backgroundColor = ' #549ec5';
	setTimeout(() => {
		cartItem.style.left = '-60px';
	}, 200);
}
cartItem.parentNode.onmouseleave = function() {
	setTimeout(() => {
		cartItem.style.left = '0';
	}, 200);
	setTimeout(() => {
		cartItem.previousElementSibling.style.backgroundColor = ' #7a6e6e';
	}, 400);
	
}

feedbackItem.parentNode.onmouseover = function() {
	feedbackItem.previousElementSibling.style.backgroundColor = ' #549ec5';
	setTimeout(() => {
		feedbackItem.style.left = '-60px';
	}, 100);
}
feedbackItem.parentNode.onmouseleave = function() {
	setTimeout(() => {
		feedbackItem.style.left = '0';
	}, 100);
	setTimeout(() => {
		feedbackItem.previousElementSibling.style.backgroundColor = ' #7a6e6e';
	}, 400);
}
toTopItem.parentNode.onmouseover = function() {
	toTopItem.previousElementSibling.style.backgroundColor = ' #549ec5';
	setTimeout(() => {
		toTopItem.style.left = '-60px';
	}, 100);
}
toTopItem.parentNode.onmouseleave = function() {
	setTimeout(() => {
		toTopItem.style.left = '0';
	}, 100);
	setTimeout(() => {
		toTopItem.previousElementSibling.style.backgroundColor = ' #7a6e6e';
	}, 400);
}